Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
set of sets and "in" operator

I was doing some coding exercises and I ended up using a set of frozensets. Here is the code:

cities = 4
roads = [[0, 1], [1, 2], [2, 0]]
roads = set([frozenset(road) for road in roads])
    
output = []
    
for i in range(cities-1):
    for j in range(i+1, cities):
        if set([i,j]) not in roads:
            output.append([i,j])

As you can see, the if in the nested for tests for the presence of the set in the set of sets. However, it was my understanding that in this case, hashables need to be used with the in operator.

If I replace set([i,j]) with [i,j], I do get the following error:

TypeError: unhashable type: 'list'

So, here is my question: why does it work with the set, which is not (as far as I know) hashable and not with the list? Should it not also throw an error, what am I missing?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Nevermind, found the answer in the documentation, for anyone wondering:

Note, the elem argument to the __contains__(), remove(), and discard() methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem.

over 4 years ago · Santiago Trujillo Relatório

0

From my reading of the CPython source it appears that the test for contains checks if the key is found in the set; if not, and if the key is a set object, an attempt is made to convert the key to a frozenset, and then that key is tested. The same behavior exists for operations like remove, as seen here:

>>> s = set([frozenset([1,2])])
>>> s
{frozenset({1, 2})}
>>> s.remove(set([1,2]))
>>> s
set()

The code in question in the interpreter is the set_contains() function in Objects/setobject.c.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda